package engine;

import views.GamePlayView;
import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.widget.Toast;

import com.tetris.project.Game;
import com.tetris.project.Music;
import com.tetris.project.R;
import com.tetris.project.Shr_Res;
import framework.Physics;
import framework.interfaces.Movable.Side;
import framework.interfaces.Rotable.Direction;


@SuppressWarnings("unused")
public class GameThread extends Thread {

	SurfaceHolder mSurfaceHolder;
	Context mContext;
	boolean mRunning;
	int mCanvasWidth, mCanvasHeight;
	long mLastTime;
	GamePlayView view;
	public GamePlayScene mScene;

	public GameThread(SurfaceHolder holder, Context context, GamePlayView theView)
	{
		mSurfaceHolder = holder;
		mContext = context;
		mRunning = false;
		view = theView;
		mScene = new GamePlayScene(mContext);
	}

	public boolean keyDown(int keyCode)
	{
		synchronized (mScene) {
			if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_Q) {
				mScene.getPiece().move(Side.LEFT);
				//if(Shr_Res.sfx){buttonSound.playButtonSound(R.raw.chimes);}
			} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_W) {
				mScene.getPiece().move(Side.RIGHT);
				//if(Shr_Res.sfx){buttonSound.playButtonSound(R.raw.chimes);}
			} else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
				mScene.getPiece().rotate(Direction.CLOCKWISE);
				//if(Shr_Res.sfx){buttonSound.playButtonSound(R.raw.chimes);}
			}
		}
		return true;
	}

	public boolean keyUp(int keyCode, KeyEvent event)
	{
		return true;
	}

	public void setRunning(boolean run)
	{
		mRunning = run;
	}
		
	@Override
	public void run() {
		Physics.init(framework.Physics.getVelocity(), GamePlayView.mWindowHeight, mScene.getPiece());
		//Log.d(Shr_Res.TAG, "Physics.init mWindowHeight = " + GamePlayView.mWindowHeight);
		Canvas c;
		while (mRunning && !Game.gameOver) {
			c = null;
			try {
				c = mSurfaceHolder.lockCanvas();
				synchronized (mSurfaceHolder) {
					mScene.draw(c);
					Physics.updatePhysics(System.currentTimeMillis()+100);
					Thread.sleep(0);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			finally {
				if (c != null) {
					mSurfaceHolder.unlockCanvasAndPost(c);
				}
			}
		}
	}
}
